#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int data;
    struct Node *next;
    struct Node *prev;
} Node_t, *Node_p;

Node_p createNode(int data)
{
    Node_p node = (Node_p)malloc(sizeof(Node_t));
    node->data = data;
    node->next = NULL;
    node->prev = NULL;
    return node;
}

Node_p findNode(Node_p head, int pos)
{
    Node_p temp = head->next;
    if (pos < 0)
    {
        return NULL;
    }
    while (pos > 0)
    {
        if (temp->next == NULL)
        {
            return NULL;
        }
        else
        {
            temp = temp->next;
            pos--;
        }
    }
    return temp;
}

void printNode(Node_p head)
{
    Node_p temp = head->next;
    while (temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int getCount(Node_p head)
{
    int count = 0;
    Node_p temp = head->next;
    while (temp != NULL)
    {
        count++;
        temp = temp->next;
    }
    return count;
}

void insertNode(Node_p head, int data, int pos)
{
    if (pos < 0 || pos > count_node(head))
    {
        printf("pos error\n");
        return;
    }
    Node_p newNode = Node_create(data);
    Node_p currNode = Node_find(head, pos);

    if (currNode == NULL)
    {
        if (count_node(head) == 0)
        {
            head->next = newNode;
        }
        else
        {
            Node_p lastNode = Node_find(head, count_node(head) - 1);
            lastNode->next = newNode;
            newNode->prev = lastNode;
        }
    }
    else
    {
        Node_p prevNode = currNode->prev;
        if (prevNode == NULL)
        {
            newNode->next = currNode;
            currNode->prev = newNode;
            head->next = newNode;
        }
        else
        {
            newNode->next = currNode;
            newNode->prev = prevNode;
            prevNode->next = newNode;
            currNode->prev = newNode;
        }
    }
}

void deleteNode(Node_p head, int pos)
{
    if (pos < 0 || pos >= count_node(head))
    {
        printf("pos error\n");
        return;
    }
    Node_p currNode = Node_find(head, pos);
    Node_p prevNode = currNode->prev;
    Node_p nextNode = currNode->next;
    if (prevNode == NULL)
    {
        if (nextNode == NULL)
        {
            head->next = NULL;
        }
        else
        {
            head->next = nextNode;
            nextNode->prev = NULL;
        }
    }
    else
    {
        if (nextNode == NULL)
        {
            prevNode->next = NULL;
        }
        else
        {
            prevNode->next = nextNode;
            nextNode->prev = prevNode;
        }
        free(currNode);
    }
}
